import cv2

# TO CHANGE!
img_file = "image/203.jpg"

points = []
scale_x = scale_y = 1.0

def mouse_callback(event, x, y, flags, param):
    global points, img_display, scale_x, scale_y

    if event == cv2.EVENT_LBUTTONDOWN:
        if len(points) < 2:
            # 映射到原始图坐标
            orig_x = int(x / scale_x)
            orig_y = int(y / scale_y)
            points.append((orig_x, orig_y))
            print(f"点 {len(points)}: ({orig_x}, {orig_y})")

            # 画在显示图上（缩放版）
            cv2.circle(img_display, (x, y), 5, (0, 255, 0), -1)
            if len(points) == 2:
                prev_x = int(points[0][0] * scale_x)
                prev_y = int(points[0][1] * scale_y)
                cv2.line(img_display, (prev_x, prev_y), (x, y), (0, 0, 255), 2)

            cv2.imshow("image", img_display)

def main():
    global img_display, points, scale_x, scale_y
    name = img_file.split("/")[-1].split("\\")[-1].split(".")[-2]
    img = cv2.imread(img_file)  # 原图
    if img is None:
        print("读取图片失败")
        return

    # 缩放到固定 600×800（宽×高）
    target_w, target_h = 800, 450
    scale_x = target_w / img.shape[1]
    scale_y = target_h / img.shape[0]
    img_display = cv2.resize(img, (target_w, target_h))

    cv2.namedWindow("image")
    cv2.setMouseCallback("image", mouse_callback)
    cv2.imshow("image", img_display)

    while True:
        key = cv2.waitKey(1) & 0xFF
        if key == 13:  # Enter
            if len(points) == 2:
                dx = points[1][0] - points[0][0]
                dy = points[1][1] - points[0][1]
                print(f"位置向量: ({dx}, {dy})")

                with open(name+"_posivec.txt", "w") as f:
                    f.write(f"{dx}, {dy}\n")
                print(f"已保存到 {name}_posivec.txt")
            else:
                print("请先点击两个点！")
            break
        elif key == ord('q'):
            break

    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
